#import "ColdAppDelegate.h"
#import "UpdateManager.h"
#import <CoreData/CoreData.h>
#import "UMSocialData.h"
#import "WXApi.h"
#import "BaseNavigationController.h"
#import "JokeViewController.h"
#import "JudgeViewController.h"
#import "PostViewController.h"
#import "TopicViewController.h"
#import "JudgeViewController.h"
#import "SettingViewController.h"
#import "SplashManager.h"
#import "NetWorkManager.h"
#import "RegexKitLite.h"

@implementation ColdAppDelegate

@synthesize window = _window;
@synthesize mainController;
@synthesize menuViewController;
@synthesize jokeNavController;
@synthesize topicNavController;
//@synthesize judgeNavController;
@synthesize postNavController;
//@synthesize settingNavController;

#pragma mark -
#pragma mark Application lifecycle

- (void)dealloc {
    PP_RELEASE(_window);
    PP_RELEASE(splashView);
    PP_RELEASE(mainController);
    PP_RELEASE(menuViewController);
    PP_RELEASE(jokeNavController);
    PP_RELEASE(topicNavController);
    PP_RELEASE(postNavController);
    [super dealloc];
}



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    NSString *name = @"splash2013-03-09-v2.jpg,splash2013-03-08-v1.jpg,splash2013-03-07-v2.jpg,splash2013-03-06-v1.jpg,splash2013-03-05-v1.jpg,";

    NSString *today = @"splash2013-03-07";
    NSString *str = [NSString stringWithFormat:@"%@-v\\d+?.jpg",today];
    
    //\\d+(?=.jpg)
    NSString * str1 = [name stringByMatching:str];

    
    NSLog(@"str111111111:%@",str1);
    
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    JokeViewController *home = [[JokeViewController alloc] initWithNibName:@"JokeViewController" bundle:nil];
    home.homeWindow = self.window;
    self.jokeNavController = [[BaseNavigationController alloc] initWithRootViewController:home];
    
    TopicViewController *topic = [[TopicViewController alloc] initWithNibName:@"TopicViewController" bundle:nil];
    self.topicNavController = [[BaseNavigationController alloc] initWithRootViewController:topic];
    [topic release];
    
    PostViewController *post = [[PostViewController alloc] initWithNibName:@"PostViewController" bundle:nil];
    self.postNavController = [[BaseNavigationController alloc] initWithRootViewController:post];
    [post release];
    
    self.menuViewController = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil];
    mainController =  [[IIViewDeckController alloc] initWithCenterViewController:self.jokeNavController
                                                                                    leftViewController:self.menuViewController
                                                                                   rightViewController:nil];
//    /* To adjust speed of open/close animations, set either of these two properties. */
//    deckController.openSlideAnimationDuration = 0.5f;
//    deckController.closeSlideAnimationDuration = 0.5f;
    mainController.leftSize = 44.0;
    
    self.window.rootViewController = mainController;
    UIApplication *app = [UIApplication sharedApplication];
    [app setStatusBarStyle: UIStatusBarStyleBlackOpaque];
    self.window.rootViewController.view.layer.cornerRadius = 4;
    self.window.rootViewController.view.layer.masksToBounds = YES;
    
    [WXApi registerApp:WEIXIN_APPKEY];
    
    [UMSocialData setAppKey:UMENG_APPKEY];
//    [UMSocialData openLog:YES];  //分享的log提示
    
    [MobClick startWithAppkey:UMENG_APPKEY reportPolicy:REALTIME channelId:nil];

    LoggerSetOptions(NULL, kLoggerOption_LogToConsole);
    
    [[UpdateManager sharedInstance] checkVersion:NO :home];
    [home release];
    
//	[self performSelector:@selector(installUncaughtExceptionHandler) withObject:nil afterDelay:0];

    [self.window makeKeyAndVisible];
    [self loadingAnimation];

    return YES;
}

-(UINavigationController *)judgeNavController {
    JudgeViewController *judge = [[JudgeViewController alloc] initWithNibName:@"JudgeViewController" bundle:nil];
    UINavigationController *res = [[BaseNavigationController alloc] initWithRootViewController:judge];
    [judge release];
    return res;
}

-(UINavigationController *)settingNavController {
    SettingViewController *setting = [[SettingViewController alloc] initWithNibName:@"SettingViewController" bundle:nil];
    UINavigationController *res = [[BaseNavigationController alloc] initWithRootViewController:setting];
    [setting release];
    return res;
}

+ (ColdAppDelegate *)sharedAppDelegate {
    return (ColdAppDelegate *) [UIApplication sharedApplication].delegate;
}



- (void)loadingAnimation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom ] == UIUserInterfaceIdiomPhone) {
        // Make this interesting.
        splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 320, 480)];
        
        if ([[[SplashManager sharedInstance]getSplashImageName] isEqualToString:@"false"]) {
            splashView.image = [UIImage imageNamed:@"Default.png"];
        }else{
            NSString *filePath = [SPLASH_IMAGE_FOLDER stringByAppendingPathComponent:[[SplashManager sharedInstance]getSplashImageName]];
            splashView.image = [UIImage imageWithContentsOfFile:filePath];
        }
        
        [self.window addSubview:splashView];
        [self.window bringSubviewToFront:splashView];
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:1.0f];
        [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.window cache:YES];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(startupAnimationDone:finished:context:)];
        splashView.alpha = 0.0;
        splashView.frame = CGRectMake(-320 * 0.5, -480 * 0.5, 320 * 2, 480 * 2);
        [UIView commitAnimations];
    }else {
        splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 768, 1024)];
        splashView.image = [UIImage imageNamed:@"Default_iPad.png"];
        [self.window addSubview:splashView];
        [self performSelector:@selector(startupAnimationDone:finished:context:) withObject:nil afterDelay:2];
    }
    
//splash下载图片功能：
//    if ([[NetWorkManager sharedInstance]hasNetwork]) {
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            [[SplashManager sharedInstance]downloadSplashImages];
//        });
//    }

}

- (void)startupAnimationDone:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    [splashView removeFromSuperview];
    [splashView release];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    Log(@"UIApplication 短的:%@.....:%@",application,url);
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    Log(@"UIApplication 长的:%@.....:%@",application,url);
    return  [WXApi handleOpenURL:url delegate:self];
}


#pragma mark -
#pragma mark UITabBarControllerDelegate methods

// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
}

// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}

//<<<<<<< HEAD
//
//    //新浪微博登录
//    loginController = [[LoginViewController alloc]init];
//    sinaWeiboLogin = [[SinaWeibo alloc] initWithAppKey:kAppKey appSecret:kAppSecret appRedirectURI:kAppRedirectURI andDelegate:loginController];
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    NSDictionary *sinaweiboInfo = [defaults objectForKey:@"SinaWeiboAuthData"];
//    if ([sinaweiboInfo objectForKey:@"AccessTokenKey"] && [sinaweiboInfo objectForKey:@"ExpirationDateKey"] && [sinaweiboInfo objectForKey:@"UserIDKey"])
//    {
//        sinaWeiboLogin.accessToken = [sinaweiboInfo objectForKey:@"AccessTokenKey"];
//        sinaWeiboLogin.expirationDate = [sinaweiboInfo objectForKey:@"ExpirationDateKey"];
//        sinaWeiboLogin.userID = [sinaweiboInfo objectForKey:@"UserIDKey"];
//    }
//
//    Log(@"appLication delegate :%@.....:%@",sinaWeiboLogin,sinaWeiboLogin.delegate);
//
//
//=======

@end

